package com.lanou3g.demo.servlet;

import com.lanou3g.demo.base.BaseServlet;
import com.lanou3g.demo.dao.UserDao;
import com.lanou3g.demo.entity.UserEntity;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "UserServlet",urlPatterns = "/user/*")
public class UserServlet extends BaseServlet {

    // 付款页面
    public void orderDesc(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("WEB-INF/jsps/order/desc.jsp").forward(request,response);
    }

    // 用户注册
    public void register(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException {
        String uid = request.getParameter("uid");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String code = request.getParameter("code");

        UserEntity user = UserDao.selectUser(username);
        if (user != null){
            response.sendRedirect(request.getContextPath()+"/main/userRegist");
        }else {
            System.out.println(username);
            System.out.println(password);
            System.out.println(email);

            UserDao.addUser(uid,username,password,email,code);

            response.sendRedirect(request.getContextPath()+"/main/userLogin");
        }



    }

    // 用户登入
    public void login (HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        UserEntity user = UserDao.selectUser(username);

       if (user != null){
           if (password.equals(user.getPassword())){
               HttpSession session = request.getSession();
               session.setMaxInactiveInterval(10000);
               session.setAttribute("uid",user.getUid());
               System.out.println(user.getUid());
               response.sendRedirect("/main");
           }else {
               response.sendRedirect(request.getContextPath()+"/main/userLogin");
           }
       }else {
           response.sendRedirect(request.getContextPath()+"/main/userRegist");
       }

    }


}
